<?php
namespace app\common\model;
use think\Db;
use think\Cache;
use think\Loader;
use think\Config;
class Member extends \think\Model 
{
    protected $type = [
        'more' => 'array',
    ];
    protected $name = 'member';
    protected $autoWriteTimestamp = true;
    protected $auto = ['ip'];
    protected $update = ['last_login_ip','delete_time'];
    
    public function setIpAttr($value)
    {
        return request()->ip();
    }
    public function setPasswordAttr($value)
    {
        return preg_match("/^(###)/",$value)?$value:st_password($value);
    }
    public function setLastLoginIpAttr($value)
    {
        return request()->ip();
    }
    public function setDeleteTimeAttr($value)
    {
        return empty($value)?0:$value;
    }
    //个人注册事务处理
    public function addPersonal($data,$member,$detail){
        $transStatus = false;
        $member =!empty($member->data)?$member->data:null;
        //$detail =!empty($detail->data)?$detail->data:null;
        //启动事务
        Db::startTrans();
        try{
            $this->isUpdate(false)->save($member);
            $mid           = $this->getLastInsID(); 
            $detail['mid'] = $mid;
            $memberDetail =new MemberDetail();
            $memberDetail ->allowField(true)->isUpdate(false)->save($detail);
            if(empty($data['openid'])){
                $wxMember = new \app\common\model\WxMember();
                $wx['mid']     = $mid;
                $wx['open_id'] = $data['openid'];
                $wxMember ->allowField(true)->isUpdate(false)->save($wx);
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::record($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }
    //用户绑定openid
    public function binding($openId,$mid){
        return Db::name('wx_member') ->where('open_id', $openId)->update(['mid' => $mid]);
        
    }
    
    
    //查找推荐人信息
    public function findReferee($mobile){
         $member =Db::name('member') ->where('mobile', $mobile)->find();
         if(empty($member['referee_mobile'])){
             return null;
         }else{
             return self::getMemberByMobile($member['referee_mobile']);
         }    
    }
    public function personalUpdate($personal){   
        $transStatus = false;
        Db::startTrans();
        try{
            
            $this->allowField(['real_name','id_card'])->isUpdate(true)->save($personal,['id' => $personal['mid']]);
            $memberDetail = new MemberDetail();
            unset($personal['real_name']);
            unset($personal['id_card']);
            $memberDetail ->where('mid', $personal['mid'])->update($personal);
            
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::record($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;               
    }
    
    //企业注册事务处理
    public function addCompany($data,$member,$detail){
        $transStatus = false;
        $member =!empty($member->data)?$member->data:null;
        //$detail =!empty($detail->data)?$detail->data:null;
        //启动事务
        Db::startTrans();
        try{
            $this->isUpdate(false)->save($member);
            $mid           = $this->getLastInsID();
            $detail['mid'] = $mid;
            $companyDetail =new CompanyDetail();
            $companyDetail ->allowField(true)->isUpdate(false)->save($detail);
            if(empty($data['openid'])){
                $wxMember = new \app\common\model\WxMember();
                $wx['mid']     = $mid;
                $wx['open_id'] = $data['openid'];
                $wxMember ->allowField(true)->isUpdate(false)->save($wx);
            }
            $transStatus = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::record($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $transStatus;
    }
    public function checkValidateionCode($mobile,$code){
        $mobileCode= Cache::get('mobileCode');
        if(!empty($mobileCode["$mobile"])&&$mobileCode["$mobile"]==$code){
            unset($mobileCode["$mobile"]);
            Cache::set('mobileCode',$mobileCode,300);
            return true;
        }else {
            return false;
        }
        
    }
    public function createQrcode($mid){
        Loader::import('phpqrcode.phpqrcode');
        $data = $mid;
        $level = 'L';// 纠错级别：L、M、Q、H
        $size = 6;// 点的大小：1到10,用于手机端4就可以了
        $QRcode = new \QRcode();
        ob_start();
        $QRcode->png($data,false,$level,$size,0);
        $imageString = base64_encode(ob_get_contents());
        ob_end_clean();
        //echo '<img src="data:image/png;base64,'.$imageString.'" />';
        return 'data:image/png;base64,'.$imageString;
    }
    //动态码登录
    public function dynamicLogin($member){
        $field ='id_card,id,real_name,password,pay_password,referee_mobile,mobile,company_name,licence_number,legal_person,type,user_status';
    
        if($member['type']==1){//个人会员
            $field = 'gold_card,silver_card,bank_name,bank_card';
            $memberDetail = new \app\common\model\MemberDetail();
            unset($member['company_name']);
            unset($member['licence_number']);
            unset($member['legal_person']);
            $member['pay_password']  = empty($member['pay_password'])?0:1; //支付密码为空 赋值为0
            $member['emptyPassword'] = empty($member['password'])?1:2; //密码为空 emptyPassword赋值为1
            $detail = $memberDetail ->where('mid',$member['id'])->field( $field)->find();
            if(!empty($detail)){
                $xcxResult = array_merge($member,$detail->getData());
            }else {
                $xcxResult = $member;
            }
    
        }else {
            unset($member['real_name']);//释放真实姓名
            $field = 'gold_card,silver_card,bank_name,bank_card';
            $companyDetail = new \app\common\model\CompanyDetail();
            $detail = $companyDetail ->where('mid',$member['id'])->field( $field)->find();
            if(!empty($detail)){
                $xcxResult = array_merge($member,$detail->getData());
            }else {
                $xcxResult = $member;
            }
        }
        return $xcxResult;
    }
    //用户名和密码登录
    public function login($mobile,$psw){         
        $where = [
            "mobile"  => $mobile,
            "password"=> $psw
        ];
        $field ='id_card,id,real_name,password,pay_password,referee_mobile,mobile,company_name,licence_number,legal_person,type,user_status';
        $member  = Db::name('member') ->where($where) ->field($field)->find();
        
        if($member['type']==1){//个人会员
            $field = 'gold_card,silver_card,bank_name,bank_card';
            $memberDetail = new \app\common\model\MemberDetail();
            unset($member['company_name']);
            unset($member['licence_number']);
            unset($member['legal_person']);
            $member['pay_password']  = empty($member['pay_password'])?0:1; //支付密码为空 赋值为0
            $member['emptyPassword'] = empty($member['password'])?1:2; //密码为空 emptyPassword赋值为1
            $detail = $memberDetail ->where('mid',$member['id'])->field( $field)->find(); 
            if(!empty($detail)){
                $xcxResult = array_merge($member,$detail->getData());
            }else {
                $xcxResult = $member;
            }
        
        }else {
            unset($member['real_name']);//释放真实姓名
            $field = 'gold_card,silver_card,bank_name,bank_card';
            $companyDetail = new \app\common\model\CompanyDetail();
            $detail = $companyDetail ->where('mid',$member['id'])->field( $field)->find();
            if(!empty($detail)){
                $xcxResult = array_merge($member,$detail->getData());
            }else {
                $xcxResult = $member;
            }
        }
        return $xcxResult;
    }
    public function setPassword($mobile,$psw){
        $member  = Db::name('member')->where('mobile', $mobile)->update(['password' => $psw]);        
        return $member;
    }
    //重置密码
    public function resetPassword($mobile,$field,$password){
        $member  = Db::name('member')->where('mobile', $mobile)->update([$field => $password]);
        return $member;
    }
    //设置支付密码
    public function setPayPassword($mobile,$payPsw){
        $member  = Db::name('member')->where('mobile', $mobile)->update(['pay_password' => $payPsw]);
        return $member;
    }
    public function getMemberByMobile($mobile){
        
        $field ='id_card,id,real_name,password,pay_password,referee_mobile,mobile,company_name,licence_number,legal_person,type,user_status,phone_status,bank_status,referee_moblie_status';
        $result = $this->where('mobile', $mobile)->field( $field)->find(); 
        if(empty($result)){
            return null;
        }
        if($result['type']==1){//个人会员
            $field = 'gold_card,silver_card,bank_name,bank_card';
            $memberDetail = new \app\common\model\MemberDetail();
            unset($result['company_name']);
            unset($result['licence_number']);
            unset($result['legal_person']);
            $detail = $memberDetail ->where('mid',$result['id'])->field( $field)->find();
            if(!empty($detail)){
                $xcxResult = array_merge($result->getData(),$detail->getData());
            }else {
                $xcxResult = $result;
            }
        
        }else {
            unset($result['real_name']);//释放真实姓名
            $field = 'gold_card,silver_card,bank_name,bank_card';
            $companyDetail = new \app\common\model\CompanyDetail();
            $detail = $companyDetail ->where('mid',$result['id'])->field( $field)->find();
            if(!empty($detail)){
                $xcxResult = array_merge($result->getData(),$detail->getData());
            }else {
                $xcxResult = $result;
            }
        }
        return $xcxResult;  
    }
    /**
     * 密码加密方法
     * @param string $pw 要加密的原始密码
     * @param string $authCode 加密字符串
     * @return string
     */
    function st_password($pw, $authCode = '')
    {
        if (empty($authCode)) {
            $authCode = Config::get('database.authcode');
        }
        $result = "###" . md5(md5($authCode . $pw));
        return $result;
    }
    /** 文件转base64输出
     * @param  String $file 文件路径
     * @return String base64 string
     */
    function fileToBase64($file){
        $base64_file = '';
        if(file_exists($file)){
            $mime_type= mime_content_type($file);
            $base64_data = base64_encode(file_get_contents($file));
            $base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
        }
        return $base64_file;
    }
}
